const http = require('http');
const chalk = require('chalk');
const path = require('path');
const route = require('./helper/route');
const conf = require('./config/defaultConfig');
const openUrl = require('./helper/openUrl');

//将app作为模块使用有两点好处
//第一，将此模块导入到 index里，作为功能模块，和cli相连
//第二，可作为独立的模块，被其他地方调用
class Server {
    constructor (config) {
        this.conf = Object.assign({}, conf, config);
    }

    start () {
        const server = http.createServer((req, res) => {
            const filePath = path.join(this.conf.root, req.url);
            route(req, res, filePath, this.conf)
        });

        server.listen(this.conf.port, this.conf.hostname, () => {
            const addr = `http://${this.conf.hostname}:${this.conf.port}`;
            console.info(`Server started at ${chalk.green(addr)}`);
            openUrl(addr);
        });
    }
}

module.exports = Server;

